package com.mfz.common.encryption.simple

import com.mfz.common.encryption.Encryption
import com.mfz.common.encryption.EncryptionMode
import java.util.*
import kotlin.experimental.xor

/**
 * 这是一个简单的加密的公钥
 *
 */
class SimpleEncryptPublic(publicKey: String) : Encryption {
	private val mode: ByteArray = getPublicByte(Base64.getDecoder().decode(publicKey))

	override fun getMode(): String {
		return EncryptionMode.SIMPLE.name
	}

	override fun encrypt(planText: String): String {
		val textBytes = planText.toByteArray()

		var j = 60
		for (i in textBytes.indices) {
			textBytes[i] = textBytes[i].xor(mode[j])
			if (j < 122) j++ else j = 60
		}

		return Base64.getEncoder().encodeToString(textBytes)
	}

	override fun decrypt(cipherText: String): String {
		val textBytes = Base64.getDecoder().decode(cipherText)

		var j = 0
		for (i in textBytes.indices) {
			textBytes[i] = textBytes[i].xor(mode[j])
			if (j < 64) j++ else j = 0
		}

		return String(textBytes)
	}
}

/**
 * 自己的加密操作的私钥部分
 *
 * create by 2019-03-21.
 * @author yimin
 */
class SimpleEncyrptPrivate(privateKey: String) : Encryption {
	private val mode: ByteArray = Base64.getDecoder().decode(privateKey)

	override fun getMode(): String {
		return EncryptionMode.SIMPLE.name
	}

	override fun encrypt(planText: String): String {
		val textBytes = planText.toByteArray()

		var j = 0
		for (i in textBytes.indices) {
			textBytes[i] = textBytes[i].xor(mode[j])
			if (j < 64) j++ else j = 0
		}

		return Base64.getEncoder().encodeToString(textBytes)
	}

	override fun decrypt(cipherText: String): String {
		val textBytes = Base64.getDecoder().decode(cipherText)

		var j = 60
		for (i in textBytes.indices) {
			textBytes[i] = textBytes[i].xor(mode[j])
			if (j < 122) j++ else j = 60
		}

		return String(textBytes)
	}
}

var next = System.currentTimeMillis()

/**
 * 生成一个私钥。
 */
fun generatorSimplePrivateKey(seed: Long): String {
	val bytes = ByteArray(123)

	next += seed
	for (i in bytes.indices) {
		//生成一个伪随机数
		next = (next * 1103515245 + 12345) / 65536 % 32768
		bytes[i] = next.toByte()
	}

	return Base64.getEncoder().encodeToString(bytes)
}


fun generatorSimplePublicKey(privateKey: String): String {
	var bytes = Base64.getDecoder().decode(privateKey)

	bytes = getPublicByte(bytes)

	return Base64.getEncoder().encodeToString(bytes)
}

private fun getPublicByte(bytes: ByteArray): ByteArray {
	for (i in 0..60) {
		bytes[i] = bytes[i] xor bytes[123 - 61 + i]
	}
	return bytes
}